package com.siyoumi.app.modules.app_menu.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.siyoumi.app.entity.SysAbc;
import com.siyoumi.app.service.SysAbcService;
import com.siyoumi.component.http.InputData;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.controller.AdminApiController;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/xadmin/app_menu/app_menu__menu__list")
public class app_menu__menu__list
        extends AdminApiController {
    @GetMapping()
    public XReturn index() {
        setPageTitle("菜单列表");

        SysAbcService app = SysAbcService.getBean();

        InputData inputData = InputData.fromRequest();
        String compKw = inputData.input("compKw");

        JoinWrapperPlus<SysAbc> query = app.listQuery(XHttpContext.getAppId(), false);
        //join
        query.leftJoin(SysAbc.table() + " AS type", "type.abc_id", "t_s_abc.abc_pid");
        query.eq("t_s_abc.abc_table", "app_menu_item");
        query.select("t_s_abc.*", "type.abc_name AS type1_name");

        if (XStr.hasAnyText(compKw)) { //名称
            query.like("t_s_abc.abc_name", compKw);
        }

        IPage<SysAbc> page = new Page<>(inputData.getPageIndex(), inputData.getPageSize());
        //list
        IPage<Map<String, Object>> pageData = app.getMaps(page, query);
        List<Map<String, Object>> list = pageData.getRecords();
        long count = pageData.getTotal();

        List<Map<String, Object>> listData = list.stream().map(data ->
        {
            SysAbc entity = app.loadEntity(data);
            data.put("id", entity.getKey());

            return data;
        }).collect(Collectors.toList());

        getR().setData("list", listData);
        getR().setData("count", count);
        return getR();
    }


    //删除
    @Transactional
    @PostMapping("/del")
    public XReturn del(String[] ids) {
        if (ids.length <= 0) {
            return EnumSys.ERR_VAL.getR("至少选择1项");
        }

        SysAbcService app = SysAbcService.getBean();
        QueryWrapper<SysAbc> query = app.listQuery(XHttpContext.getAppId(), false)
                .eq("abc_table", "app_menu_item")
                .in("abc_id", Arrays.asList(ids));
        boolean delCount = app.remove(query);

        return XReturn.getR(0);
    }
}
